using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;

namespace XProject.Util
{
    class Encryptor
    {
        public static string MD5Encrypt(string strSource)
        {
            byte[] srcBytes = null;
            byte[] encodedByte=null;
           
            try
            {
                MD5 md5 = new MD5CryptoServiceProvider();
                srcBytes = ASCIIEncoding.Default.GetBytes(strSource);                
                encodedByte = md5.ComputeHash(srcBytes);                
            }
            catch (Exception ex)
            {
            }
            return BitConverter.ToString(encodedByte).Replace("-","").ToLower();
          
        }
        public static string Encrypt(string toEncrypt, string key)
        {
            byte[] keyArr;
            byte[] toEncryptArr = UTF8Encoding.UTF8.GetBytes(toEncrypt);
  
                MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
                keyArr =md5.ComputeHash( UTF8Encoding.UTF8.GetBytes(key));
                md5.Clear();         
            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
            
            tdes.Key = keyArr;
            tdes.Mode = CipherMode.ECB;
            tdes.Padding = PaddingMode.ISO10126;
            ICryptoTransform cTransform = tdes.CreateEncryptor();
            byte[] rsArr = cTransform.TransformFinalBlock(toEncryptArr, 0, toEncryptArr.Length);

            tdes.Clear();
            return Convert.ToBase64String(rsArr);
        }
        public static string Decrypt(string cypherString, string key)
        {
            byte[] keyArr = null;
            byte[] encryptedArr = null;
            encryptedArr = Convert.FromBase64String(cypherString);
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();

            keyArr = md5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
            md5.Clear();

            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
           
            tdes.Key = keyArr;
            tdes.Padding = PaddingMode.ISO10126;
            tdes.Mode = CipherMode.ECB;
            ICryptoTransform cTransform = tdes.CreateDecryptor();
            byte[] resultArr = cTransform.TransformFinalBlock(encryptedArr, 0, encryptedArr.Length);
            tdes.Clear();
            return UTF8Encoding.UTF8.GetString(resultArr);

        }
    }
}
